//
//  QSHomeHeaderView.m
//  DigitalEconomy_iOS
//
//  Created by Ding on 2020/3/18.
//  Copyright © 2020 DingC. All rights reserved.
//

#import "QSHomeHeaderView.h"
#import "QSHomeHeaderItemCell.h"
#import "QSHomeItemFlowLayout.h"
#import "QSHomeInterface.h"
#import <TXScrollLabelView.h>
#import "QSSingInInterface.h"
#import "QSNotificationDetailModel.h"
#import "QSOSSUploadHelper.h"
#import "QSUserInterface.h"
#import "QSHomeEntranceSliderView.h"

static NSString *imageKey = @"imageKey";
static NSString *titleKey = @"titleKey";
static NSString *itemId = @"itemID";
static NSString *ic_leadership = @"home_leadership";
static NSString *leadTitle = @"领导驾驶舱";

static NSString *ic_enterpriseArchives = @"home_enterprise_Archives";
static NSString *enterpriseTitle = @"一企一档";

static NSString *ic_problemdealing = @"home_problemdeal";
static NSString *problemDealTitle = @"问题处理";

static NSString *ic_problemsend = @"home_sendproblem";
static NSString *problemSendTitle = @"问题上报";

static NSString *ic_signin = @"home_signin";
static NSString *signTitle = @"驻企签到";

static NSString *ic_visit = @"home_visit";
static NSString *visitTitle = @"企业走访";

@interface QSHomeHeaderView ()<UICollectionViewDelegate,UICollectionViewDataSource, TXScrollLabelViewDelegate>

//阴影视图
@property (nonatomic, strong)UIView *shadowView;
/** 入口collectionView */
@property (nonatomic, strong) UICollectionView *collectionView;

/** 灰线*/
@property (nonatomic, strong) UIView *grayLine;

//@property (nonatomic, strong) QSHomeEntranceSliderView *sliderView;

@property (nonatomic, strong) QSHomeItemFlowLayout *layout;

@property (nonatomic, strong) NSArray *noticeList;

/** 通知内容label*/
@property (nonatomic, strong) UILabel *contentLabel;

@property (nonatomic, strong) TXScrollLabelView *scrollLabel;

@property (nonatomic, strong) NSDictionary *userDic;
@property (nonatomic, assign)NSInteger itemCount;
//更多按钮
@property (nonatomic, strong)UIButton *moreButton;
@end

static NSString * const KHomeItemCell = @"KHomeItemCell";

@implementation QSHomeHeaderView

- (void)loadData {
  [self getUserInfo];//用户信息
  [self getNotificationList];//通知信息
  [self getCompanyList];//获取企业信息保存在本地UserModel
  [self getUserLevel];//获取用户级别 1为服务人员 2为组长 3为领导 4.领导不可签到
  [self getUserPermissions];//获取用户权限（判断item）
}

#pragma mark - **************** Initials
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor QSColorWhiteFFFFFF];
        self.layer.cornerRadius = 5;
        [self configSubView];
        [self loadData];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateUI) name:@"CHANGE_USERIMAGEFINISH" object:nil];
    }
    return self;
}

- (void)configSubView{
    [self addSubview:self.headerBackgroundImageView];
    
    [self.headerBackgroundImageView addSubview:self.userIconImageView];
    [self.headerBackgroundImageView addSubview:self.nameLabel];
    [self.headerBackgroundImageView addSubview:self.enterpriseLabel];
    [self.headerBackgroundImageView addSubview:self.rightImageView];
    [self addSubview:self.shadowView];
    [self.shadowView addSubview:self.collectionView];
    
    [self addSubview:self.notificationButton];
    [self addSubview:self.moreButton];
    [self addSubview:self.grayLine];
//    [self addSubview:self.scrollLabel];
    [self addSubview:self.contentLabel];
//    self.scrollLabel.frame = CGRectMake(1, 1, kScreenWidth, 30);
    
    [self configLayout];
}


- (void)configLayout{
    
    [_headerBackgroundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.top.width.equalTo(self);
        make.width.offset(kScreenWidth);
        make.height.offset(kScreenWidth *kHomeHeaderProportion);
//        make.height.mas_equalTo(self.height * kHomeHeaderImageProportion);
//        make.height.offset(163);
    }];
    
    [_userIconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerBackgroundImageView).offset(kRealValue(25 + kStatusBarHeight));
        make.left.equalTo(self.headerBackgroundImageView).offset(kRealValue(24));
        make.width.height.offset(kRealValue(44));
    }];
    [_nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerBackgroundImageView).offset(kStatusBarHeight + kRealValue(29));
        make.left.equalTo(self.userIconImageView.mas_right).offset(kRealValue(10));
    }];
    [_enterpriseLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.nameLabel.mas_bottom).offset(kRealValue(5));
        make.left.equalTo(self.userIconImageView.mas_right).offset(kRealValue(10));
    }];
    [_rightImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.headerBackgroundImageView.mas_trailing).offset(- kRealValue(24));
        make.centerY.equalTo(self.userIconImageView);
        make.width.height.offset(kRealValue(25));
    }];
    
    
    [_notificationButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(kRealValue(10));
        make.bottom.equalTo(self).offset(- kRealValue(9.5));
        make.width.offset(kRealValue(60));
        make.height.offset(kRealValue(20));
    }];
    [_grayLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.notificationButton.mas_right).offset(kRealValue(8));
        make.centerY.equalTo(self.notificationButton);
        make.width.offset(kRealValue(0.5));
        make.height.offset(kRealValue(11));
    }];
    [_moreButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_notificationButton);
        make.right.equalTo(self).offset(- kRealValue(10));
    }];
   
    [_contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.grayLine.mas_right).offset(kRealValue(9));
        make.centerY.equalTo(self.notificationButton);
        make.width.offset(kRealValue(100));
        make.height.offset(kRealValue(30));
    }];
    [_shadowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.notificationButton.mas_top).offset(- kRealValue(17));
        make.left.equalTo(self).offset(kRealValue(10));
        make.right.equalTo(self).offset(- kRealValue(10));
        make.height.offset(kRealValue(110));
    }];
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.width.equalTo(_shadowView);
        make.height.mas_equalTo(kRealValue(98));
    }];
  
//    [self.sliderView mas_makeConstraints:^(MASConstraintMaker *make) {
//      make.top.mas_equalTo(self.collectionView.mas_bottom);
//      make.centerX.mas_equalTo(0.f);
//      make.size.mas_equalTo(CGSizeMake(kRealValue(60.f), kRealValue(4.f)));
//    }];
}

#pragma mark - 懒加载
- (UIImageView *)headerBackgroundImageView{
    if (!_headerBackgroundImageView) {
        
        _headerBackgroundImageView = [[UIImageView alloc]init];
        
        _headerBackgroundImageView.userInteractionEnabled = YES;
        [_headerBackgroundImageView setImage:[UIImage imageNamed:@"ic_homeheder"]];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectBackImageView:)];        
        [self.headerBackgroundImageView addGestureRecognizer:tap];
        _headerBackgroundImageView.layer.masksToBounds = YES;
        _headerBackgroundImageView.contentMode = UIViewContentModeScaleToFill;
    }
    return _headerBackgroundImageView;
}

- (UIImageView *)userIconImageView{
    if (!_userIconImageView) {
        _userIconImageView = [[UIImageView alloc]init];
        _userIconImageView.layer.cornerRadius = 22;
        _userIconImageView.layer.masksToBounds = YES;
        _userIconImageView.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _userIconImageView;
}

- (UILabel *)nameLabel{
    if (!_nameLabel) {
        _nameLabel = [UILabel labelWithName:@"" font:[UIFont QSFontOfSize16] textColor:[UIColor QSColorWhiteFFFFFF] textAlignment:NSTextAlignmentLeft];
    }
    return _nameLabel;
}

- (UILabel *)enterpriseLabel{
    if (!_enterpriseLabel) {
        _enterpriseLabel = [UILabel labelWithName:@"" font:[UIFont QSFontOfSize12] textColor:[UIColor QSColorWhiteFFFFFF] textAlignment:NSTextAlignmentLeft];
    }
    return _enterpriseLabel;
}

- (UIImageView *)rightImageView{
    if (!_rightImageView) {
        _rightImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ic_home_arrow"]];
//        _rightImageView.backgroundColor = [UIColor QSColorWhiteFFFFFF];
    }
    return _rightImageView;
}

- (UIButton *)notificationButton{
    if (!_notificationButton) {
        _notificationButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        [_notificationButton setTitle:@"消息通知" forState:UIControlStateNormal];
        [_notificationButton setImage:[UIImage imageNamed:@"ic_home_notification"] forState:UIControlStateNormal];
        [_notificationButton setTitleColor:[UIColor QSColorBlue166EFF] forState:UIControlStateNormal];
        [_notificationButton.titleLabel setFont:[UIFont QSFontOfSize14]];
        [_notificationButton addTarget:self action:@selector(notificationButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _notificationButton;
}

- (UIView *)grayLine{
    if (!_grayLine) {
        _grayLine = [[UIView alloc]init];
        _grayLine.backgroundColor = [UIColor QSColorGrayDADBDF];
    }
    return _grayLine;
}

- (UILabel *)contentLabel{
    if(!_contentLabel){
        _contentLabel = [UILabel labelWithName:@"暂无公告" font:[UIFont QSFontOfSize14] textColor:[UIColor QSColorBlack666666] textAlignment:NSTextAlignmentLeft];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(contentLabelAction:)];
        self.contentLabel.userInteractionEnabled = YES;
        [self.contentLabel addGestureRecognizer:tap];
    }
    return _contentLabel;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _layout = [[QSHomeItemFlowLayout alloc]init];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_layout];
        _collectionView.backgroundColor = [UIColor QSColorWhiteFEFEFF];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.layer.cornerRadius = 5;
        [_collectionView registerClass:[QSHomeHeaderItemCell class] forCellWithReuseIdentifier:KHomeItemCell];
        _collectionView.layer.masksToBounds = YES;
        _collectionView.layer.shadowColor = [UIColor QSColorGrayA1A1A1].CGColor;
        _collectionView.layer.shadowOffset = CGSizeMake(0, 0);
        _collectionView.layer.shadowOpacity = 0.2f;
        _collectionView.layer.shadowRadius = 10;
        _collectionView.showsHorizontalScrollIndicator = NO;
    }
    return _collectionView;
}

- (UIView *)shadowView{
    if (!_shadowView) {
        _shadowView = [[UIView alloc]init];
        _shadowView.backgroundColor = [UIColor QSColorWhiteFEFEFF];
        _shadowView.layer.cornerRadius = 5;
        _shadowView.layer.masksToBounds = NO;
        _shadowView.layer.shadowColor = [UIColor QSColorGrayA1A1A1].CGColor;
        _shadowView.layer.shadowOffset = CGSizeMake(0, 0);
        _shadowView.layer.shadowOpacity = 0.2f;
        _shadowView.layer.shadowRadius = 10;
    }
    return _shadowView;
}

- (UIButton *)moreButton{
    if (!_moreButton) {
        _moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_moreButton setTitle:@"更多>" forState:UIControlStateNormal];
        _moreButton.titleLabel.font = [UIFont QSFontOfSize14];
        [_moreButton setTitleColor:[UIColor QSColorGrayC1D1E8] forState:UIControlStateNormal];
        [_moreButton addTarget:self action:@selector(notificationButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _moreButton;
}

//- (QSHomeEntranceSliderView *)sliderView {
//  if (!_sliderView) {
//    _sliderView = [[QSHomeEntranceSliderView alloc] init];
//    [self addSubview:_sliderView];
//  }
//  return _sliderView;
//}

#pragma mark - **************** Private Methods
- (NSArray *)noticeMsgListByParkNoticeList:(NSArray *)noticeList {
    NSMutableArray *noticeMsgList = [NSMutableArray arrayWithCapacity:0];
    NSInteger index = 0;
    for (QSNotificationDetailModel *notiModel in noticeList) {
        if (notiModel.imTitle
            && index <= 6) {
            [noticeMsgList addObject:notiModel.imTitle];
        }
        index++;
    }
    NSLog(@"----%@", noticeMsgList);
    return noticeMsgList;
}

#pragma mark - Action

- (void)selectBackImageView:(UITapGestureRecognizer *)sender{
    NSLog(@"点击了背景图");
    if (self.delegate && [self.delegate respondsToSelector:@selector(homeHeaderView:didSelectBackgroundPicture:)]) {
        [self.delegate homeHeaderView:self didSelectBackgroundPicture:1];
    }
}

- (void)notificationButtonAction:(UIButton *)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(homeHeaderViewDidClickNotificationButton:)]) {
        [self.delegate homeHeaderViewDidClickNotificationButton:self];
    }
}

- (void)contentLabelAction:(UITapGestureRecognizer *)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(homeHeaderViewDidClickNotificationButton:)]) {
           [self.delegate homeHeaderViewDidClickNotificationButton:self];
       }
}
#pragma mark - ***************** TXScrollLabelViewDelegate
- (void)scrollLabelView:(TXScrollLabelView *)scrollLabelView didClickWithText:(NSString *)text atIndex:(NSInteger)index {
    QSNotificationDetailModel *model = self.noticeList[index];
    if (self.delegate && [self.delegate respondsToSelector:@selector(homeHeaderViewDidClickNotificationTitle:imId:)]) {
        [self.delegate homeHeaderViewDidClickNotificationTitle:self imId:model.imId];
    }
}
#pragma mark - CollectionViewDelegate && DataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.itemArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    QSItemModel *model = self.itemArray[indexPath.item];
    QSHomeHeaderItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:KHomeItemCell forIndexPath:indexPath];
    cell.itemModel = model;
    return cell;
}

- (void)checkItemCountWithArray:(NSArray *)itemArr{
    self.itemArray = itemArr.mutableCopy;
    NSLog(@"item数组：%@", self.itemArray);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    QSItemModel *model = self.itemArray[indexPath.item];
    if (self.delegate && [self.delegate respondsToSelector:@selector(homeHeaderView:navigationCollectionViewdidSelectItemAtIndexPath:itemModel:)]) {
        [self.delegate homeHeaderView:self navigationCollectionViewdidSelectItemAtIndexPath:indexPath itemModel:model];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    [_layout invalidateLayout];
    CGFloat itemW = kScreenWidth - kRealValue(20);
    CGFloat percent = (scrollView.contentOffset.x + itemW)/scrollView.contentSize.width;
//    [self.sliderView updateSliderViewWithPercent:percent];
}


#pragma mark - Api
- (void)getUserInfo{
    [QSHomeInterface getUserInfoAndBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSDictionary * _Nonnull result) {
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            self.userDic = result;
            QSUserModel *user = [QSUserManager sharedQSUserManager].user;
            user.name = self.userDic[@"name"];
            user.headPic = self.userDic[@"headPic"];
            user.phone = self.userDic[@"phone"];
            user.townshipName = self.userDic[@"townshipName"];
            user.roleName = self.userDic[@"roleName"];//角色名
            [[QSUserManager sharedQSUserManager] saveUser:user];
            [self updateUI];
        }
        
    }];
}

- (void)getUserPermissions{
    [QSHomeInterface getUserpermissionsAndBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, QSUserHomeItemModel * _Nonnull result) {
        if(rspStatusAndMessage.code == kResponseSuccessCode){
            [self checkItemCountWithArray:result.iconList];
            if (result.epType) {//epType为1 驻企服务员 epType为2 乡镇联企干部  epType为3 区联企领导
                kCurrentUser.epType = result.epType;
                [[QSUserManager sharedQSUserManager] saveUser:kCurrentUser];
            }
            [self.collectionView reloadData];
            dispatch_async(dispatch_get_main_queue(), ^{
              [self scrollViewDidScroll:self.collectionView];
            });
        }
    }];
}

- (void)getNotificationList{
    [QSHomeInterface getNotificationListWithPageIndex:1 andBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, QSNotificationModel * _Nonnull resultModel) {
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            NSLog(@"通知数组%@", resultModel.list);
          [self configXscroll];
            self.noticeList = resultModel.list;
        }
    }];
}

- (void)configXscroll{
  [self.scrollLabel removeFromSuperview];
  self.scrollLabel = [[TXScrollLabelView alloc] initWithTextArray:[self noticeMsgListByParkNoticeList:_noticeList] type:TXScrollLabelViewTypeFlipNoRepeat velocity:2.5 options:UIViewAnimationOptionCurveEaseInOut inset:UIEdgeInsetsMake(0, 0, 0, 0)];
          _scrollLabel.scrollLabelViewDelegate = self;
          _scrollLabel.scrollTitleColor = [UIColor QSColorBlack6C6C6C];
          _scrollLabel.font = [UIFont QSFontOfSize14];
          _scrollLabel.textAlignment = NSTextAlignmentLeft;
  //        _scrollLabel.backgroundColor = [UIColor greenColor];
          _scrollLabel.backgroundColor = [UIColor QSColorWhiteFFFFFF];
          NSLog(@"text:%@", [self noticeMsgListByParkNoticeList:_noticeList]);
    [self addSubview:self.scrollLabel];
    self.scrollLabel.frame = CGRectMake(1, 1, kScreenWidth, 30);
    [_scrollLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.grayLine.mas_right).offset(kRealValue(9));
        make.right.equalTo(self.moreButton.mas_left).offset(- kRealValue(9));
        make.centerY.equalTo(self.notificationButton);
        make.height.offset(kRealValue(30));
    }];
}
- (void)getCompanyList{
    //请求公司列表
//    [QSSingInInterface getCompanyListWithPageIndex:1 andBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, QSBindingEnterprisesModel * _Nonnull result) {
//        if (rspStatusAndMessage.code == kResponseSuccessCode && result) {            
//            NSLog(@"当前绑定公司列表：%@", result.list);
//        }
//    }];
    
}

- (void)getUserLevel{
    [QSHomeInterface getUserLevelAndBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSDictionary * _Nonnull result) {
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            QSUserModel *model = [[QSUserManager sharedQSUserManager] user];
            model.enterpriseLevel = (NSString *)result;
//            NSString *roleName;
            if (model.enterpriseLevel.integerValue == 1) {
//                roleName = @"驻企服务员";
            }else if (model.enterpriseLevel.integerValue == 2){
//                roleName = @"组长";
            }else{
//                roleName = @"领导";
            }
//            model.roleName = roleName;
            [[QSUserManager sharedQSUserManager] saveUser:model];
            NSLog(@"当前级别为%@", model.enterpriseLevel);
        }
    }];
}


-(void)setNoticeList:(NSArray *)noticeList{
    _noticeList = noticeList;
    self.contentLabel.hidden = noticeList.count;
    self.scrollLabel.hidden = !noticeList.count;
    if (noticeList.count) {
        [self.scrollLabel beginScrolling];
    }
    if (noticeList.count == 1) {
        [self.scrollLabel endScrolling];
    }
}

//更新UI
- (void)updateUI{
    QSUserModel *user = [QSUserManager sharedQSUserManager].user;
    if (user.headPic && user.headPic.length > 1) {
        [self.userIconImageView sd_setImageWithURL:[NSURL URLWithString:user.headPic]];
    }else{
        UIImage *defaulUserIcon = [UIImage imageNamed:@"user_defult_icon"];
        [self.userIconImageView setImage:defaulUserIcon];
        //传到阿里云 并设置为默认头像
        [self setDefaultUsericonWithAliOSSWithImage:defaulUserIcon];
    }
    [self.nameLabel setText:user.name];
    [self.enterpriseLabel setText:user.roleName];
}
//未设置图片则把默认头像上传到阿里云
- (void)setDefaultUsericonWithAliOSSWithImage:(UIImage *)image{
    [QSOSSUploadHelper asyncUploadFilesToOSS:@[image] complete:^(NSArray<NSString *> * _Nullable names, NSError * _Nullable error) {
        if (!error) {
            NSString *imageUrl = names.lastObject;
            DLog(@"%@", imageUrl);
//            上传到自己服务器
            [self changeUserImageWithImageUrl:imageUrl];
        }else{
        }
    }];
}
//发送到服务器更换
- (void)changeUserImageWithImageUrl:(NSString *)imageUrl{
    [QSUserInterface changeUserImageWithImageUrl:imageUrl AndBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSDictionary * _Nonnull result) {
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            kCurrentUser.headPic = imageUrl;
            [[QSUserManager sharedQSUserManager] saveUser:kCurrentUser];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"CHANGE_USERIMAGEFINISH" object:nil];
        }else{
            
        }
    }];
}


- (void)dealloc{
    //移除观察者
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
